package com.example.slogantv.OkHttpNetwork;

import android.content.Context;
import android.os.Handler;
import android.util.Log;
import com.example.slogantv.utlis.AppUtils;
import com.example.slogantv.utlis.SignUtils;
import org.json.JSONObject;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class Network {
    private OkHttpClient mClient;
    private Handler mHandler = new Handler();
    //登录之后返回的Token字符串
    private String mToken = "";
    public volatile static Network network;

    public Network() {
        getmClient();
    }

    private OkHttpClient getmClient() {
        //配置了网络请求的超时时间
        mClient = new OkHttpClient().newBuilder()
                .connectTimeout(3, TimeUnit.SECONDS)
                .readTimeout(3, TimeUnit.SECONDS)
                .writeTimeout(3, TimeUnit.SECONDS)
                .build();
        return mClient;
    }

    public static Network getInstance() {
        if (network == null) {
            Class var0 = Network.class;
            synchronized (Network.class) {
                if (network == null) {
                    network = new Network();
                }
            }
        }
        return network;
    }

    //格式化Map
    private JSONObject addJosns(Map<Object, Object> hashMap) {
        try {
            JSONObject jsonObject = new JSONObject(hashMap);
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void performGet(final Context context, Map<Object, Object> hashMap, String head, String Url, final NetCallBack netCallBack){
        String strUrl = head+Url ;
        final StringBuffer buff = new StringBuffer("");
     //   requestHead(type,context);
        if (hashMap != null) {
            boolean isFirst = true;
            for (Map.Entry<Object, Object> entry : hashMap.entrySet()){
                if (isFirst) {
                    buff.append("" + entry.getKey() + "=" + String.valueOf(entry.getValue()));
                    isFirst = false;
                } else {
                    buff.append("&" + entry.getKey() + "=" + String.valueOf(entry.getValue()));
                }
            }
        }
        Log.i("----接口==" , strUrl+buff);
        Log.i("----mToken-----：" , mToken);

        Map<String, String> map = new HashMap<>();
        map.put("clientType", "1");
        map.put("version", AppUtils.packageName(context));
        map.put("appId", "1");
        Long timestamp = System.currentTimeMillis();
        map.put("timestamp", timestamp.toString());
        String sign = SignUtils.serviceSign(Url, "GET", map, hashMap, null);
        Request request = new Request.Builder()
                .url(strUrl + "?" + buff.toString())
                .addHeader("Authorization", "12345")
                .addHeader("clientType", "1")//token
                .addHeader("brand", "1")//token
                .addHeader("version", AppUtils.packageName(context))//token
                .addHeader("versionCode", AppUtils.packageCode(context) + "")//token
                .addHeader("appId", "1")//token
                .addHeader("timestamp", timestamp.toString())//token
                .addHeader("sign", sign.replaceAll("\n", ""))
                .build();
        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        netCallBack.onNetFailure();
                    }
                });

            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                doResponse(context, response, netCallBack);
            }
        });

    }





    /**
     * @param context     上下文 预留
     * @param head        API头部
     * @param hashMap     参数
     * @param mUrl        请求地址
     * @param netCallBack 请求回调
     */
    public void performPost(final Context context,
                            final String head,
                            Map<Object, Object> hashMap,
                            String mUrl,
                            final NetCallBack netCallBack) {
        try {
            String json = addJosns(hashMap).toString();
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(JSON, json);
            Map<String, String> map = new HashMap<>();
            map.put("clientType", "1");
            map.put("version",  AppUtils.packageName(context));
            map.put("appId", "1");
            Long timestamp = System.currentTimeMillis();
            map.put("timestamp", timestamp.toString());
            String sign = SignUtils.serviceSign( head, "POST", map, new HashMap<Object, Object>(), json.getBytes());
            Log.i("----参数==" , json);
            Log.i("----head-----：" ,mUrl+head);
            final Request request = new Request.Builder()
                    .url(mUrl + head)
                    .addHeader("Authorization",  "12345")//token
                    .addHeader("clientType", "1")//token
                    .addHeader("brand", "1")//token
                    .addHeader("version", AppUtils.packageName(context))//token
                    .addHeader("versionCode", AppUtils.packageCode(context) + "")//token
                    .addHeader("appId", "1")//token
                    .addHeader("timestamp", timestamp.toString())//token
                    .addHeader("sign", sign.replaceAll("\n", ""))
                    .post(body)
                    .build();
            mClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(okhttp3.Call call, IOException e) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            netCallBack.onNetFailure();
                            Log.i("TAG", "run: 网络有异常："+e.toString());
                            //  MyToastUtil.showShort(context, "哎呀，网络走丢了哟");
                        }
                    });
                    doFailure(netCallBack);
                }

                @Override
                public void onResponse(okhttp3.Call call, Response response) throws IOException {
                    doResponse(context, response, netCallBack);
                }

            });
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    netCallBack.onError("未知错误");
                }
            });
        }
    }

    /**
     * 处理失败
     *
     * @param netCallBack
     */
    private void doFailure(final NetCallBack netCallBack) {

    }

    /**
     * 成功
     *
     * @param context
     * @param response
     * @param netCallBack
     */
    private void doResponse(final Context context, Response response, final NetCallBack netCallBack) {
        String result = null;
        try {
            //服务器返回200~399，请求成功
            result = response.body().string();
            Log.d("服务返回结果:" , result);
            final JSONObject jsonObject = new JSONObject(result);
            //final boolean success = jsonObject.getBoolean("status");
            //data可能为空
            if (jsonObject.toString().length()>0) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        netCallBack.onSuccess(jsonObject);
                    }
                });

            } else {
                final String finalResult = jsonObject.toString();
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        netCallBack.onError(finalResult);
                    }
                });


            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    netCallBack.onError("未知错误");
                    //  MyToastUtil.showShort(context, "哎呀，网络走丢了哟~");
                }
            });
        }

    }

    /**
     * 回调接口
     */
    public interface NetCallBack {

        //网络请求失败，没连网
        void onNetFailure();

        //网络请求成功
        void onSuccess(JSONObject result);

        //网络请求成功但数据异常
        void onError(String result);
    }


}
